<template>
  <div class="body">
    <!-- 整体 -->
    <div class="container right-panel-active">
      <!-- 登录 -->
      <div class="container_from container--signup">
        <el-form :model="loginForm" class="from" id="from1" status-icon :rules="loginRules" ref="loginForm"
                 label-width="55px">
          <a class="from_title">登录</a>
          <el-form-item label="用户名" prop="userName">
            <el-input placeholder="请输入用户名" type="text" v-model="loginForm.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" style="position: relative">
            <el-input placeholder="请输入密码" type="password" v-model="loginForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verificationCode">
            <el-input placeholder="请输入验证码" v-model="loginForm.verificationCode">
              <template slot="append">
                <div class="img-box">
                  <el-image
                      @click="getVerificationCode"
                      class="code-img"
                      :src="verificationCode.dataUrl"
                      fit="fill">
                  </el-image>
                </div>
              </template>
            </el-input>
            <el-checkbox class="check-box" v-model="checked" :disabled="disabledRemember" @change="changeRemember">记住密码</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button class="button" type="primary" @click="submitForm('loginForm',1)">登录
            </el-button>
            <el-button class="button" @click="resetForm(1)">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 注册 -->
      <div class="container_from container--signin" v-show="visible">
        <el-form :model="registerForm" class="from" id="from2" status-icon :rules="registerRules"
                 ref="registerForm"
                 label-width="70px">
          <a class="from_title">注册</a>
          <el-form-item label="用户名" prop="userName">
            <el-input placeholder="请输入用户名" type="text" v-model="registerForm.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" type="password" v-model="registerForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="nextPassword">
            <el-input placeholder="请再次输入密码" type="password" v-model="registerForm.nextPassword"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verificationCode">
            <el-input placeholder="请输入验证码" v-model="registerForm.verificationCode" autocomplete="off">
              <template slot="append">
                <div class="img-box">
                  <el-image
                      @click="getVerificationCode"
                      class="code-img"
                      :src="verificationCode.dataUrl"
                      fit="fill">
                  </el-image>
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div>
              <el-button class="button" type="primary" @click="submitForm('registerForm',flag = 0)">
                注册
              </el-button>
              <el-button class="button" @click="resetForm(0)">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 遮罩层 -->
      <div class="container-overlay">
        <div class="overlay">
          <div class="overlay_panel overlay-left">
            <button type="button" class="btn" id="signin">没有账号，点击注册</button>
          </div>

          <div class="overlay_panel overlay-right">
            <button type="button" class="btn" id="signup">已有账号，直接登录</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapActions} from "vuex";
import {getUserInfo, login, registerUser} from "@/api/user";
import MessageUtil from "@/utils/MessageUtil";
import LoadingUtil from "@/utils/LoadingUtil";
import md5 from 'js-md5';
import DeepCopyUtil from "@/utils/DeepCopyUtil";
import {getVerificationCode} from "../../api/user";

export default {
  name: 'Login',
  data() {
    var validateUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'));
      } else {
        callback();
      }
    };
    var validateNextPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('确认密码不能为空'));
      } else {
        callback();
      }
    };
    var validateVerificationCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('验证码不能为空'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      flag: 1,
      checked: false,
      visible: false,
      loginForm: {
        userName: '',
        password: '',
        verificationCode: ''
      },
      registerForm: {
        userName: '',
        password: '',
        nextPassword: '',
        verificationCode: ''
      },
      verificationCode: {
        flagKey: '',
        dataUrl: '',
      },
      loginRules: {
        userName: [
          {validator: validateUserName, trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        verificationCode: [
          {validator: validateVerificationCode, trigger: 'blur'}
        ],
      },
      registerRules: {
        userName: [
          {validator: validateUserName, trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        nextPassword: [
          {validator: validateNextPassword, trigger: 'blur'}
        ],
        verificationCode: [
          {validator: validateVerificationCode, trigger: 'blur'}
        ],
      }
    };
  },
  computed: {
    disabledRemember() {
      return !this.checked && (!this.loginForm.userName || !this.loginForm.password)
    }
  },
  methods: {
    submitForm(formName, flag) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (flag === 1) {
            this.login();
          } else {
            this.registerUser()
          }
        } else {
          return false;
        }
      });
    },
    resetForm(flag) {
      if (flag === 0) {
        this.registerForm = {}
      } else {
        this.loginForm = {}
      }
    },
    login() {
      let loading = LoadingUtil.loading('正在登录中...');
      let form = DeepCopyUtil.copy(this.loginForm);
      form.password = md5(form.password)
      form.flagKey = this.verificationCode.flagKey
      login(form).then(res => {
        if (res.code === 200) {
          let token = res.data.token;
          window.sessionStorage.setItem('token', token)
          setTimeout(() => {
            this.getUserInfo(token);
            loading.close();
            MessageUtil.success('登录成功')
          }, 1000)
        } else {
          setTimeout(() => {
            loading.close();
            MessageUtil.error(res.message)
            this.resetVerificationCode()
          }, 1000)
        }
      }).catch(err => {
        setTimeout(() => {
          loading.close();
          MessageUtil.error('登陆失败')
        }, 1000)
      })
    },
    registerUser() {
      if (this.registerForm.password !== this.registerForm.nextPassword) {
        MessageUtil.error("两次输入密码不相同!");
        return;
      }
      let loading = LoadingUtil.loading('正在注册中...');
      let form = DeepCopyUtil.copy(this.registerForm);
      form.password = md5(this.registerForm.password);
      form.flagKey = this.verificationCode.flagKey
      registerUser(form).then(res => {
        if (res.code === 200) {
          setTimeout(() => {
            this.resetForm(0)
            document.getElementById("signup").click()
            MessageUtil.success(res.message)
            loading.close();
          })
        } else {
          setTimeout(() => {
            this.resetVerificationCode()
            MessageUtil.error(res.message)
            loading.close();
          }, 1000)
        }
      }).catch(err => {
        setTimeout(() => {
          MessageUtil.error('注册失败')
          loading.close();
        }, 1000)
      })
    },
    getUserInfo(token) {
      getUserInfo({token}).then(res => {
        if (res.code === 200) {
          this.setUserInfo(res.data)
          this.$router.push({path: '/home'});
        }
      })
    },
    getVerificationCode() {
      getVerificationCode().then(res => {
        if (res.code === 200) {
          this.verificationCode = res.data
        }
      }).catch(err => {

      })
    },
    handleKeyDown(event) {
      if (event.key === 'Enter') {
        if (this.flag === 1) {
          this.submitForm('loginForm', 1)
        } else {
          this.submitForm('registerForm', 0)
        }
      }
    },
    changeRemember() {
      if (this.checked) {
        window.localStorage.setItem("username", this.loginForm.userName)
        window.localStorage.setItem("password", this.loginForm.password)
      } else {
        window.localStorage.removeItem("username")
        window.localStorage.removeItem("password")
      }
    },
    loadUserInfo() {
      this.loginForm.userName = window.localStorage.getItem('username')
      this.loginForm.password = window.localStorage.getItem('password')
      if (this.loginForm.userName && this.loginForm.password) {
        this.checked = true;
      }
    },
    resetVerificationCode() {
      this.getVerificationCode()
      this.registerForm.verificationCode = ''
      this.loginForm.verificationCode = ''
    },
    init() {
      // 初始化登录框动画
      const siginBtn = document.getElementById('signin')
      const sigupBtn = document.getElementById('signup')
      const container = document.querySelector(".container")

      siginBtn.addEventListener("keydown", function (event) {
        if (event.key === "Enter") {
          event.preventDefault();
        }
      });

      sigupBtn.addEventListener("keydown", function (event) {
        if (event.key === "Enter") {
          event.preventDefault();
        }
      });

      siginBtn.addEventListener('click', (e) => {
        container.classList.remove("right-panel-active")
        this.visible = true
        this.resetVerificationCode()
        this.flag = 0
      })

      sigupBtn.addEventListener('click', (e) => {
        container.classList.add("right-panel-active")
        this.resetVerificationCode()
        this.visible = false
        this.flag = 1
      })

      //绑定键盘事件，敲击enter进行登录操作
      document.addEventListener('keydown', this.handleKeyDown);
    },
    ...mapActions('user', ['setUserInfo'])
  },
  mounted() {
    this.init();
    this.loadUserInfo()
    this.getVerificationCode()
  },
  destroyed() {
    document.removeEventListener('keydown', this.handleKeyDown);
  }
}
</script>

<style scoped>


.container--signup .el-input,
.container--signin .el-input {
  width: 225px;
}

.button {
  margin-left: 35px;
  margin-right: 35px;
  margin-top: 10px
}

a {
  font-size: 20px;
  margin-left: 100px;
  font-weight: bold;
}


.body {
  align-items: center;
  background-color: #e4e7ed;
  background: url('../../assets/images/bj.jpg');
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  /* display: flex; */
  display: grid;
  /* justify-content: center;
  align-items: center; */
  place-items: center;
}

/* h2字体 */
.from_title {
  font-weight: normal;
  margin: 0;
  margin-bottom: 1.25rem;

}

/* 忘记密码 */
.link {
  color: #333;
  font-size: 0.9rem;
  margin: 1.5rem 0;
  text-decoration: none;
}

/* 整体 */
.container {
  background-color: #e4e7ed;
  border-radius: 0.7rem;
  box-shadow: 1rem 1rem 2rem rgba(0, 0, 0, .5);
  height: 420px;
  max-height: 420px;
  max-width: 750px;
  width: 100%;
  overflow: hidden;
  position: relative;
}

/* 登陆注册表单 */
.container_from {
  height: 100%;
  position: absolute;
  top: 0;
  transition: all 0.6s ease-in-out;
}

/* 登录表单 */
.container--signin {
  left: 0;
  width: 50%;
  z-index: 2;
}

.container.right-panel-active .container--signin {
  transform: translateX(100%);
}

/* 注册表单 */
.container--signup {
  left: 0;
  opacity: 0;
  width: 50%;
  z-index: 1;
}

.container.right-panel-active .container--signup {
  animation: show 0.6s;
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
}

/* 浮层 */
.container-overlay {
  height: 100%;
  left: 50%;
  overflow: hidden;
  position: absolute;
  top: 0;
  transition: transform 0.6s ease-in-out;
  width: 50%;
  z-index: 100;
}

.container.right-panel-active .container-overlay {
  transform: translateX(-100%);
}

.overlay {
  background-color: #008997;
  background: url('../../assets/images/bj.jpg');
  /* background-color: rgba(255, 255, 255, 0.25); */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  left: -100%;
  position: relative;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
  width: 200%;
}

.container.right-panel-active .overlay {
  transform: translateX(50%);
}

.overlay_panel {
  align-items: center;
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: center;
  position: absolute;
  text-align: center;
  top: 0;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
  width: 50%;
}

.overlay-left {
  transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.overlay-right {
  right: 0;
  transform: translateX(0);
}

.container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

/* 按钮 */
.btn {
  background-color: #0367a6;
  background-image: linear-gradient(90deg, #0367a6 0%, #008997 74%);
  border-radius: 20px;
  border: 0.2px solid #0367a6;
  color: #e4e7ed;
  cursor: pointer;
  font-size: 0.8rem;
  font-weight: 700;
  letter-spacing: 0.1rem;
  padding: 1rem 4rem;
  text-transform: uppercase;
  transition: transform 80ms ease-in;
}

/*.from .btn {*/
/*    margin-top: 1.5rem;*/
/*}*/

.btn:active {
  transform: scale(0.95);
}

.btn:focus {
  outline: none;
}

.from {
  background-color: #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  /*padding: 0 3rem;*/
  height: 100%;
  text-align: center;
}

.check-box {
  position: absolute;
  left: 2px;
  top: 35px
}

.img-box {
  width: 70px;
}

.code-img {
  position: absolute;
  top: 0;
  right: 0;
  width: 70px;
  height: 38px;
}

::v-deep .el-input-group__append {
  position: relative;
  padding: 1px 1px;
}

@keyframes show {
  0%, 49.9% {
    opacity: 0;
    z-index: 5;
  }
  50%,
  100% {
    opacity: 1;
    z-index: 6;
  }
}
</style>
